﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web.Hosting;
using HandlebarsDotNet;

namespace SX.Utils
{
    public class HandlebarsMvcViewEngineFileSystem : ViewEngineFileSystem
    {
        public override string GetFileContent(string filename)
        {
            var vf = HostingEnvironment.VirtualPathProvider.GetFile("~/"+filename);

            using (var stream = vf.Open())
            using (var streamReader = new StreamReader(stream))
            {
                return streamReader.ReadToEnd();
            }
        }

        protected override string CombinePath(string dir, string otherFileName)
        {
            if (dir.ToLower().IndexOf("views/") ==-1 || dir.ToLower() != "views")
            {
                dir = Path.Combine("views", dir);
            }
            var path = Path.Combine(dir, otherFileName);
            //path = path.Replace("\\","/");
            return path;
        }

        public override bool FileExists(string filePath)
        {
            try
            {
                return HostingEnvironment.VirtualPathProvider.FileExists("~/" + filePath); 
            }
            catch (Exception)
            {
                return false;
            } 
        }
    }
}
